import React, { useState, useRef, useEffect } from 'react';
import { Form, Input, Button, Table, message, Modal, Space } from 'antd';
import { useHistory, useLocation } from 'react-router-dom';
import { CmdbContent, CmdbHeader } from '@/components';
import request from '@/utils/request';
import './index.less';

export default function TemplateAdd () {
  const [form] = Form.useForm();
  const formRef = useRef(null);
  const history = useHistory();
  const location = useLocation();
  const [dataSource, setDataSource] = useState([]);
  const [count, setCount] = useState(0);
  const [initialFormValues, setInitialFormValues] = useState({});
  const [editingTask, setEditingTask] = useState(null);
  const [isCancelModalVisible, setIsCancelModalVisible] = useState(false);
  const [processes, setProcesses] = useState([]);

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 80,
      render: (_, record, index) => index + 1,
    },
    {
      title: <span><span style={{ color: 'red' }}>*</span>进程名称</span>,
      dataIndex: "name",
      width: 250,
      render: (_, record, index) => (
        <Form.Item
          name={["processes", index, "name"]}
          rules={[{ required: true, message: "请输入进程服务名称" }]}
          style={{ marginBottom: 0 }}
        >
          <Input
            placeholder="请输入进程服务名称"
            value={record.name}
            onChange={(e) => handleInputChange(index, "name", e.target.value)}
            maxLength={100}
          />
        </Form.Item>
      ),
    },
    {
      title: '端口号',
      dataIndex: 'port',
      width: 150,
      render: (_, record, index) => (
        <Form.Item
          name={["processes", index, "port"]}
          rules={[{ required: true, message: "请输入端口号" }]}
          style={{ marginBottom: 0 }}
        >
          <Input
            placeholder="请输入端口号"
            value={record.port}
            onChange={(e) => handleInputChange(index, "port", e.target.value)}
            maxLength={100}
          />
        </Form.Item>
      ),
    },
    {
      title: '操作',
      fixed: "right",
      width: 100,
      render: (_, record) => (
        <Button
          type='link'
          onClick={() => deleteRow(record.key)}
        >
          删除
        </Button>
      ),
    },
  ];

  // 删除进程
  const deleteRow = (key) => {
    const newData = processes.filter((item) => item.key !== key);
    // 重新分配序号
    const reIndexed = newData.map((item, index) => ({
      ...item,
      id: index + 1,
    }));
    setProcesses(reIndexed);
    formRef.current?.setFieldsValue({
      processes: reIndexed,
    });
  };
  // 监听路由变化，初始化表单
  useEffect(() => {
    const { state } = location;
    if (state?.isEdit && state?.task) {
      setEditingTask(state.task);
      setDataSource(state.task.processes || []);
      setCount(state.task.processes?.length || 0);
      const formValues = {
        ossFileUploadTaskName: state.task.ossFileUploadTaskName,
        objectStoragedes: state.task.objectStoragedes,
        processes: state.task.processes || []
      };
      form.setFieldsValue(formValues);
      setInitialFormValues(formValues);
    } else {
      setEditingTask(null);
      setDataSource([]);
      setCount(0);
      form.resetFields();
    }
  }, [location, form]);
  const onAddProcess = () => {
    const newItem = {
      key: count,
      id: processes.length + 1,
      name: "",
      port: "",
      createdAt: new Date() // 添加创建时间用于排序
    };
    // 按创建时间降序排列（最新的在前面）
    const newProcesses = [newItem, ...processes];
    setProcesses(newProcesses);
    setCount(count + 1);
    // 更新表单值
    formRef.current?.setFieldsValue({
      processes: newProcesses
    });
  };
  const handleInputChange = (index, field, value) => {
    // 限制输入1-100个字
    if (value.length > 100) {
      value = value.substring(0, 100);
      message.warning("输入内容不能超过100字");
    }

    const newProcesses = [...processes];
    newProcesses[index][field] = value;
    setProcesses(newProcesses);

    // 更新表单值
    formRef.current?.setFieldsValue({
      processes: newProcesses
    });
  };
  const onSubmit = async () => {
    try {
      // 验证是否至少有一条进程
      if (processes.length === 0) {
        message.error("请至少添加1条进程");
        return;
      }

      const values = await formRef.current?.validateFields();

      // 验证每个进程的名称是否填写
      let hasError = false;
      values.processes.forEach((process, index) => {
        if (!process.name || process.name.trim().length < 1) {
          message.error(`第${index + 1}条进程名称不能为空`);
          hasError = true;
        }
      });

      if (hasError) return;

      console.log("✅ 校验通过", values);
      message.success("提交成功");
      setTimeout(()=>{
        history.goBack()
      },1000)
    } catch (errorInfo) {
      console.warn("❌ 校验失败", errorInfo);
      if (errorInfo.errorFields && errorInfo.errorFields.length > 0) {
        const firstError = errorInfo.errorFields[0];
        const fieldName = firstError.name.join(".");
        const errorDom = document.querySelector(`[name="${fieldName}"]`);
        if (errorDom && errorDom.scrollIntoView) {
          errorDom.scrollIntoView({ behavior: "smooth", block: "center" });
          errorDom.focus();
        }
      }
    }
  };

  // 确认取消操作
  const handleCancelConfirm = () => {
    // 清空表单数据
    formRef.current?.resetFields();
    // 清空进程列表
    setProcesses([]);
    setCount(0);
    message.info("已取消操作，表单数据已清空");
    setIsCancelModalVisible(false);
  };

  // 隐藏取消确认对话框
  const handleCancelModalClose = () => {
    setIsCancelModalVisible(false);
  };

  // 显示取消确认对话框
  const showCancelConfirm = () => {
    setIsCancelModalVisible(true);
  };
  return (
    <CmdbContent>
      <Space>
        <Button type='link' onClick={() => history.goBack()}>返回</Button>
        <CmdbHeader title={editingTask ? '编辑模块模版' : '新建模块模版'} />
      </Space>

      <div className='back-white padding-10'>
        <div className='padding-10'>
          <Form
            onFinish={onSubmit}
            scrollToFirstError={{
              behavior: "smooth",
              block: "center",
            }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            ref={formRef}
            initialValues={{ processes }}
          >
            {/* 基础信息部分 */}
            <div className="form-section">
              <h3>基础信息</h3>

              <Form.Item
                label="模板名称"
                name="templateName"
                rules={[{ required: true, message: "请输入模板名称" },
                { max: 20, message: "模板名称不能超过20字" }]}
              >
                <Input placeholder="请输入模板名称，最多不超过20字" />
              </Form.Item>

              <Form.Item
                label="模板描述"
                name="templateDescription"
                rules={[
                { max: 50, message: "模板描述不能超过50字" }]}
              >
                <Input
                  placeholder="请输入模板描述，最多不超过50字"
          
                />
              </Form.Item>
            </div>

            {/* 进程服务部分 */}
            <div className="form-section">
              <h3>进程服务</h3>

              <Table
                dataSource={processes}
                columns={columns}
                pagination={false}
                rowKey="key"
                scroll={{ x: 600 }}
                locale={{
                  emptyText: "暂无进程，请点击添加按钮"
                }}
                title={() => (
                  <Button
                    onClick={onAddProcess}
                  >
                    添加进程
                  </Button>
                )}
              />
            </div>
            {/* 操作按钮 */}
            <div className="form-actions">
              <Space>
                <Button onClick={showCancelConfirm}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </div>
          </Form>
        </div>
        {/* 取消确认模态框 */}
        <Modal
          title="提示"
          open={isCancelModalVisible}
          onOk={handleCancelConfirm}
          onCancel={handleCancelModalClose}
          okText="确定"
          cancelText="取消"
          className="cancel-confirm-modal"
        >
          <div className="modal-content">
       
            <span>确认取消本次操作？</span>
          </div>
        </Modal>
      </div>
    </CmdbContent>
  );
}